package com.yl.demo.base.filter;

import com.alibaba.fastjson.JSON;
import com.yl.demo.model.UserInfo;
import com.yl.demo.utils.BaseUtil;
import com.yl.demo.utils.Result;
import com.yl.demo.utils.redis.RedisUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.cache.Cache;
import org.apache.shiro.cache.CacheManager;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.mgt.DefaultSessionKey;
import org.apache.shiro.session.mgt.SessionManager;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.AccessControlFilter;
import org.apache.shiro.web.util.WebUtils;
import org.crazycake.shiro.RedisManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.annotation.Resource;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.Serializable;
import java.util.*;

/**
 * Created by YL on 2019/10/17.
 * 前后端分离项目中，由于跨域，会导致复杂请求，即会发送preflighted request，
 * 这样会导致在GET／POST等请求之前会先发一个OPTIONS请求，但OPTIONS请求并不带shiro的'Authorization'字段
 * （shiro的Session），即OPTIONS请求不能通过shiro验证，会返回未认证的信息。
 * 解决方法：给shiro增加一个过滤器，过滤OPTIONS请求
 * isAccessAllowed：表示是否允许访问；mappedValue就是[urls]配置中拦截器参数部分，如果允许访问返回true，否则false；
 * onAccessDenied：表示当访问拒绝时是否已经处理了；如果返回true表示需要继续处理；如果返回false表示该拦截器实例已经处理了，将直接返回即可。
 * onPreHandle：会自动调用这两个方法决定是否继续处理；
 */
public class KickoutSessionControlFilter extends AccessControlFilter {

    private final static Logger logger = LoggerFactory.getLogger(CORSAuthenticationFilter.class);

    private final String X_AUTH_TOKEN = "authorizationtoken"; // AuthorizationToken x-auth-token

    @Resource
    private RedisUtils redisUtils;

    private String kickoutUrl; //踢出后到的地址

    private boolean kickoutAfter = false; //踢出之前登录的/之后登录的用户 默认踢出之前登录的用户

    private int maxSession = 1; //同一个帐号最大会话数 默认1

    private SessionManager sessionManager;

    private Cache<String, Deque<Serializable>> cache;

    public void setKickoutUrl(String kickoutUrl) {
        this.kickoutUrl = kickoutUrl;
    }

    public void setKickoutAfter(boolean kickoutAfter) {
        this.kickoutAfter = kickoutAfter;
    }

    public void setMaxSession(int maxSession) {
        this.maxSession = maxSession;
    }

    public void setSessionManager(SessionManager sessionManager) {
        this.sessionManager = sessionManager;
    }

    //设置Cache的key的前缀
    public void setCacheManager(CacheManager cacheManager) {
        this.cache = cacheManager.getCache("shiro_redis_cache");
    }

   /* @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception {
        return false;
    }*/
    @Override
    public boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception {
        //Always return true if the request's method is OPTIONSif (request instanceof HttpServletRequest) {
        if (((HttpServletRequest) request).getMethod().toUpperCase().equals("OPTIONS")) {
            return true;
        }
        return false;
    }


    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        HttpServletRequest req = (HttpServletRequest)request;
        HttpServletResponse resp = (HttpServletResponse) response;
        Subject subject = getSubject(req, resp);

        logger.info("请求URL==["+req.getRequestURI()+"]");
        if (req.getRequestURI().contains("login")) {

        }else{
            String id = WebUtils.toHttp(req).getHeader(X_AUTH_TOKEN);
            String userStr = redisUtils.get(id);
            if (!subject.isAuthenticated() && !subject.isRemembered()) {
                //如果没有登录，直接进行之后的流程
                if (StringUtils.isBlank(userStr)) {
                    this.valid(req, resp);
                    return false;
                }else{
                    logger.info("Redis 缓存有值, 直接视为有效,userStr==["+userStr+"]");
                    return true;
                }
            }
            /*if (!subject.isAuthenticated() && !subject.isRemembered()) {
                //如果没有登录，直接进行之后的流程
                // return true;
                this.valid(req, resp);
                return false;
            }*/
            Session session = subject.getSession();
            UserInfo user = (UserInfo) subject.getPrincipal();
            String username = user.getUsername();
            Serializable sessionId = session.getId();
            logger.info("Ehcahe 缓存有值, username==["+username+"], sessionId==["+sessionId+"]");

            //读取缓存   没有就存入
            Deque<Serializable> deque = cache.get(username);

            //如果此用户没有session队列，也就是还没有登录过，缓存中没有
            //就new一个空队列，不然deque对象为空，会报空指针
            if (deque == null) {
                deque = new LinkedList<Serializable>();
            }

            //如果队列里没有此sessionId，且用户没有被踢出；放入队列
            if (!deque.contains(sessionId) && session.getAttribute("kickout") == null) {
                //将sessionId存入队列
                deque.push(sessionId);
                //将用户的sessionId队列缓存
                cache.put(username, deque);
            }

            //如果队列里的sessionId数超出最大会话数，开始踢人
            while (deque.size() > maxSession) {
                Serializable kickoutSessionId = null;
                if (kickoutAfter) { //如果踢出后者
                    kickoutSessionId = deque.removeFirst();
                    //踢出后再更新下缓存队列
                    cache.put(username, deque);
                } else { //否则踢出前者
                    kickoutSessionId = deque.removeLast();
                    //踢出后再更新下缓存队列
                    cache.put(username, deque);
                }


                try {
                    //获取被踢出的sessionId的session对象
                    Session kickoutSession = sessionManager.getSession(new DefaultSessionKey(kickoutSessionId));
                    if (kickoutSession != null) {
                        //设置会话的kickout属性表示踢出了
                        kickoutSession.setAttribute("kickout", true);
                    }
                } catch (Exception e) {//ignore exception
                }
            }

            //如果被踢出了，直接退出，重定向到踢出后的地址
            if (session.getAttribute("kickout") != null) {
                //会话被踢出了
                try {
                    //退出登录
                    subject.logout();
                } catch (Exception e) { //ignore
                }
                saveRequest(request);

                Map<String, String> resultMap = new HashMap<String, String>();
                //判断是不是Ajax请求
                if ("XMLHttpRequest".equalsIgnoreCase(((HttpServletRequest) request).getHeader("X-Requested-With"))) {
                    resultMap.put("user_status", "300");
                    resultMap.put("message", "您已经在其他地方登录，请重新登录！");
                    //输出json串
                    out(response, resultMap);
                } else {
                    //重定向
                    WebUtils.issueRedirect(request, response, kickoutUrl);
                }
                return false;
            }
        }
        return true;
    }

    private void out(ServletResponse hresponse, Map<String, String> resultMap)
            throws IOException {
        try {
            hresponse.setCharacterEncoding("UTF-8");
            PrintWriter out = hresponse.getWriter();
            out.println(JSON.toJSONString(resultMap));
            out.flush();
            out.close();
        } catch (Exception e) {
            logger.info("KickoutSessionFilter.class 输出JSON异常，可以忽略。");
        }
    }

    public boolean valid(HttpServletRequest req, HttpServletResponse resp){
        try {
            logger.info("User not logged in, Please login again");
            resp.setHeader("Access-Control-Allow-Origin",  req.getHeader("Origin"));
            resp.setHeader("Access-Control-Allow-Credentials", "true");
            resp.setContentType("application/json; charset=utf-8");
            resp.setCharacterEncoding("UTF-8");
            PrintWriter out = resp.getWriter();
            Result result = new Result(20099, "User not logged in");
            out.println(BaseUtil.toJSON(result));
            out.flush();
            out.close();
        }catch (Exception e){
            e.printStackTrace();
        }
        return false;
    }
}
